#!/usr/bin/env node

const { program } = require('commander') 
const { chooseTemplate } = require('./inquirer')
const templateMap = require('./templateMap')
const download = require('download-git-repo')
const ora = require('ora')
const chalk = require('chalk')


function start() {
  program.version(require('./package.json').version) // 输出版对应的版本号

  program
    .command('create <projectName>')
    .description('用于创建一个项目模板')
    .option("-T, --template [template]", "输入使用的模板名字")
    .action(async function(projectName, options){
        let template = options.template;
        projectName = projectName || 'untitled';

        if(!template) {
          template = await chooseTemplate()
        }

        // 提示Loading
        const spinner = ora({
          text: '正在下载模板...',
          color: 'green',
          spinner: {
            interval: 80,
            frames: ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"],
          },
        })
        spinner.start();

        const downloadUrl = templateMap.get(template)

        download(downloadUrl,projectName,{clone:true},error => {
          if(error) {
            spinner.fail(`创建项目失败：${projectName}`)
            console.log('失败原因：',error)
          }else {
            spinner.succeed(`成功创建项目：${projectName}`)

            console.log(`cd ${projectName}`)
            console.log('npm install')
            console.log('npm run serve / dev')
          }
        })
    });

  program
    .command('checkAll')
    .description('查看所有的模板')
    .action(function(){
      const templateList = [
          'vue-default-template',
          'nologin-platform'
      ]
      templateList.forEach((temp,index) => {
          console.log(`(${index+1})  ${temp}`)
      })
    })

  program.parse(process.argv);

}

start()